do-while Loop in C++

Posted on December 9, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

do-while loop in C is similar to a while loop, but it guarantees that the code block is executed at least once, even if the condition is false from the beginning. The condition is checked after the code block is executed

Syntax of for Loop:

do {
// Code to be executed
} while (condition);

1. Execute the Loop Body:

    (a.) The code inside the loop is executed unconditionally for the first time, without checking any conditions.

2. Condition Check:

    (a.) After executing the loop body, the loop checks a boolean condition.

    (b.) If the condition is true, the loop body is executed again.

    (c.) If the condition is false, exit the loop.

3. Repeat Steps 1 and 2:

    (a.) If the condition is true, go back to step 1 and repeat the process.

    (b.) If the condition is false, exit the loop.

The key difference between a do-while loop and a while loop is that a do-while loop guarantees that the loop body is executed at least once, even if the condition is initially false. The condition is checked after the first iteration.

Example of do-while loop:

#include <iostream>Copy Code
using namespace std;

int main() {

    int i = 1;
    do {
        std::cout << i << " ";
        i++;
    } while (i <= 5);

    return 0;
}

In the above example, i is initially set to 1 the do-while loop executes the loop body unconditionally for the first time and inside the loop body, it prints the value of i and increments i. The loop checks the condition i <= 5 at the end of the loop body and if the condition is true, it repeats the process; if false, it exits the loop.
The output of this loop will be 1 2 3 4 5 do-while loop ensures that the loop body is executed at least once.